package com.kld.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by Dan on 2015/10/8.
 * override by cao on 2016/3/28.我没找到别的文件上传类，重用原来的。
 */
public class FileUpload {

    /**
     * 多文件上传
     * @param request
     * @param filepaths
     * @return
     */
    public static List<String> Upload(HttpServletRequest request, String[] filepaths){
        List<String> list = new ArrayList<String>();
        try{
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        System.out.println(myFileName);
                        //重命名上传后的文件名
                        String fileName = UUID.randomUUID().toString()+myFileName.substring(myFileName.lastIndexOf('.'));
                        System.out.println(fileName);
                        //定义上传路径
                        String webPath = "/upload/" + StringUtils.join(filepaths, '/');
                        String path = request.getSession().getServletContext().getRealPath(webPath);
                        File targetFile = new File(path,fileName);
                        if(!targetFile.exists()){
                            targetFile.mkdirs();
                        }
                        file.transferTo(targetFile);
                        String webFile = webPath+"/"+fileName;
                        list.add(webFile);
                    }
                }
                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
                System.out.println(finaltime - pre);
            }
            return list;
        }
        }catch (UnsupportedEncodingException ex){
            System.out.println("================================");
            System.out.println("文件上传失败");
            System.out.println("================================");
            ex.printStackTrace();
        }
        catch (IOException ex){
            System.out.println("================================");
            System.out.println("文件上传失败");
            System.out.println("================================");
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 上传单文件
     * @param request
     * @param file
     * @param filepaths
     * @return
     */
    public static String Upload2(HttpServletRequest request, MultipartFile file, String[] filepaths){
         try {

             String myFileName = file.getOriginalFilename();
             //重命名上传后的文件名
             String fileName = UUID.randomUUID().toString()+myFileName.substring(myFileName.lastIndexOf('.'));
             //定义上传路径
            String webPath = "/upload/" + StringUtils.join(filepaths, '/');
            String path = request.getSession().getServletContext().getRealPath(webPath);
            File targetfile = new File(path, fileName);
            if (!targetfile.exists()) {
                targetfile.mkdirs();
            }
            file.transferTo(targetfile);
            String webFile = webPath+"/"+fileName;
            return webFile;
        }catch (UnsupportedEncodingException ex){
            System.out.println("文件上传失败");
            System.out.println("================================");
            ex.printStackTrace();
        }
        catch (IOException ex){
            System.out.println("文件上传失败");
            System.out.println("================================");
            ex.printStackTrace();
        }
        return "";
    }
}
